package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.WorkOvertimeDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chx
 * @since 2024-01-22
 */
@Service
public class WorkOvertimeServiceImpl extends ServiceImpl<WorkOvertimeDao, WorkOvertime> implements WorkOvertimeService {

    @Resource
    private HttpServletRequest request;

    @Resource
    private WorkOvertimeTimeService workOvertimeTimeService;

    @Resource
    private WorkOvertimeDao workOvertimeDao;

    @Resource
    private BaseUserService baseUserService;

    @Override
    public Map<String, Object> getAll(WorkOvertime workOvertime, InputParam inputParam) {
        String loginUserId = SysUtil.getLoginUserId(request);
        LambdaQueryWrapper<WorkOvertime> qw = new LambdaQueryWrapper();
        qw.eq(WorkOvertime::getUserId, loginUserId);

        Page<WorkOvertime> result = this.page(new Page<WorkOvertime>(inputParam.getPage(), inputParam.getSize()), qw);
        long total = result.getTotal();
        List<WorkOvertime> list = result.getRecords();

        List<BaseDepartment> myDepartment = workOvertimeDao.getMyDepartment(loginUserId);
        BaseUser baObj = baseUserService.getById(loginUserId);

        list.forEach(obj -> {
            obj.setName(baObj.getName());
            obj.setAccount(baObj.getAccount());
            obj.setDepartment(myDepartment);
            LambdaQueryWrapper<WorkOvertimeTime> qw3 = new LambdaQueryWrapper<>();
            qw3.eq(WorkOvertimeTime::getWorkId, obj.getId());
            List<WorkOvertimeTime> list1 = workOvertimeTimeService.list(qw3);
            obj.setTimeQuantum(list1);
        });

        Collections.sort(list, new Comparator<WorkOvertime>() {
            @Override
            public int compare(WorkOvertime o1, WorkOvertime o2) {
                return o2.getOvertimeDate().compareTo(o1.getOvertimeDate());
            }
        });

        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("rows", list);
        map.put("total", total);
        return map;
    }

    @Override
    public Map<String, Object> add(WorkOvertime workOvertime) {
        workOvertime.setCreateTime(LocalDateTime.now());
        workOvertime.setId(SysUtil.UUID());
        workOvertime.setUserId(SysUtil.getLoginUserId(request));
        List<WorkOvertimeTime> list = workOvertime.getTimeQuantum();
        workOvertime.setApprovalStatus(0);

        int hours = 0;
        int minutes = 0;
        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                Duration duration = Duration.between(list.get(i).getStartTime(), list.get(i).getEndTime());
                int hour = (int) Math.abs(duration.toHours());
                int minute = (int) Math.abs(duration.toMinutes() % 60);
                hours += hour;
                minutes += minute;
            }
        }
        float workTime = (float) ((int) ((hours + (((float) minutes) / 60)) * 10) * 0.1);

        workOvertime.setOvertimeHours(workTime);
        this.save(workOvertime);

        String id = workOvertime.getId();

        workOvertime.getTimeQuantum().forEach(obj -> {
            obj.setWorkId(id);
        });

        workOvertimeTimeService.saveBatch(workOvertime.getTimeQuantum());
        return ResponseInfo.success("添加成功");
    }

    @Override
    public Map<String, Object> delete(String id) {

        if (StringUtil.iszNull(id)) {
            return ResponseInfo.error("请传入id");
        }

        boolean r1 = this.removeById(id);
        LambdaQueryWrapper<WorkOvertimeTime> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(WorkOvertimeTime::getWorkId, id);
        boolean r2 = workOvertimeTimeService.remove(qw2);

        if (!r1 || !r2) {
            return ResponseInfo.error("删除失败");
        }

        return ResponseInfo.success("删除成功");
    }

    @Override
    public Map<String, Object> edit(WorkOvertime workOvertime) {
        LambdaUpdateWrapper<WorkOvertime> luw = new LambdaUpdateWrapper<>();
        luw.eq(WorkOvertime::getId, workOvertime.getId());
        luw.set(WorkOvertime::getUpdateTime, LocalDateTime.now());
        luw.set(WorkOvertime::getOvertimeDate, workOvertime.getOvertimeDate());
        List<WorkOvertimeTime> list = workOvertime.getTimeQuantum();
        int hours = 0;
        int minutes = 0;
        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                Duration duration = Duration.between(list.get(i).getStartTime(), list.get(i).getEndTime());
                int hour = (int) Math.abs(duration.toHours());
                int minute = (int) Math.abs(duration.toMinutes() % 60);
                hours += hour;
                minutes += minute;
            }
        }
        float workTime = (float) ((int) ((hours + (((float) minutes) / 60)) * 10) * 0.1);
        luw.set(WorkOvertime::getOvertimeHours, workTime);
        this.update(workOvertime, luw);

        LambdaQueryWrapper<WorkOvertimeTime> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WorkOvertimeTime::getWorkId, workOvertime.getId());
        workOvertimeTimeService.remove(lqw);

        String id = workOvertime.getId();

        workOvertime.getTimeQuantum().forEach(obj -> {
            obj.setWorkId(id);
        });

        workOvertimeTimeService.saveBatch(workOvertime.getTimeQuantum());

        return ResponseInfo.success("修改成功");
    }

    @Override
    public Map<String, Object> detail(String id) {
        String loginUserId = SysUtil.getLoginUserId(request);
        LambdaQueryWrapper<WorkOvertime> qw = new LambdaQueryWrapper();
        qw.eq(WorkOvertime::getUserId, loginUserId);
        qw.eq(WorkOvertime::getId, id);
        WorkOvertime byId = this.getById(id);
        System.out.println(byId);

        List<BaseDepartment> myDepartment = workOvertimeDao.getMyDepartment(loginUserId);
        BaseUser baObj = baseUserService.getById(loginUserId);

        byId.setName(baObj.getName());
        byId.setAccount(baObj.getAccount());
        byId.setDepartment(myDepartment);
        LambdaQueryWrapper<WorkOvertimeTime> qw3 = new LambdaQueryWrapper<>();
        qw3.eq(WorkOvertimeTime::getWorkId, byId.getId());
        List<WorkOvertimeTime> list1 = workOvertimeTimeService.list(qw3);
        byId.setTimeQuantum(list1);

        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("data", byId);
        return map;
    }
}
